package org.dromara.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.dto.AreaDto;
import org.dromara.common.core.service.AreaService;
import org.dromara.system.domain.SysArea;
import org.dromara.system.domain.bo.SysAreaBo;
import org.dromara.system.domain.vo.SysAreaVo;
import org.dromara.system.mapper.SysAreaMapper;
import org.dromara.system.service.ISysAreaService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 地区表(SysArea)表服务实现类
 *
 * @author ckk
 * @since 2025-07-12 10:45:36
 */
@RequiredArgsConstructor
@Service
public class SysAreaServiceImpl extends ServiceImpl<SysAreaMapper, SysArea> implements ISysAreaService, AreaService {

    private final SysAreaMapper baseMapper;

    @Override
    public List<SysAreaVo> selectArea(SysAreaBo bo) {
        LambdaQueryWrapper<SysArea> wrapper = Wrappers.lambdaQuery(SysArea.class);
        wrapper.eq(bo.getId() != null, SysArea::getId, bo.getId());
        wrapper.like(StrUtil.isNotBlank(bo.getAreaName()), SysArea::getAreaName, bo.getAreaName());
        wrapper.eq(bo.getParentId() != null, SysArea::getParentId, bo.getParentId());
        wrapper.eq(bo.getParentId() == null, SysArea::getParentId, 0);
        wrapper.orderByAsc(SysArea::getId);
        List<SysAreaVo> vos = baseMapper.selectVoList(wrapper);
        vos.forEach(vo -> vo.setAdcode(StrUtil.subPre(vo.getId().toString(), 6)));
        return vos;
    }

    /**
     * 按ids获取区域名称列表
     *
     * @param areaIds 区域id
     * @return {@link String }
     */
    @Override
    public List<AreaDto> getAreaNamesByIds(List<String> areaIds) {
        LambdaQueryWrapper<SysArea> wrapper = Wrappers.lambdaQuery(SysArea.class).in(SysArea::getId, areaIds);
        List<AreaDto> areaDtos = BeanUtil.copyToList(baseMapper.selectList(wrapper), AreaDto.class);
        areaDtos.forEach(areaDto -> areaDto.setAdcode(StrUtil.subPre(areaDto.getId().toString(), 6)));
        return areaDtos;
    }

    /**
     * 通过id获取区域名称
     *
     * @param areaId 区域id
     * @return {@link String }
     */
    @Override
    public AreaDto getAreaNameById(String areaId) {
        LambdaQueryWrapper<SysArea> wrapper = Wrappers.lambdaQuery(SysArea.class).eq(SysArea::getId, areaId);
        AreaDto areaDto = BeanUtil.copyProperties(baseMapper.selectOne(wrapper), AreaDto.class);
        areaDto.setAdcode(StrUtil.subPre(areaDto.getId().toString(), 6));
        return areaDto;
    }
}

